package cn.fulong.sso.client.utils;

import cn.fulong.sso.client.constant.SSOConstants;

import javax.servlet.FilterConfig;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import java.util.Set;

/**
 * @Version 1.0
 * @Author: 云树
 * @Description:
 * @Date: 2019/3/29
 * @Modify 云树
 * @ModifyDate 2019/3/29
 * @since 1.0
 */
public class ServletConfigUtil {


    public static String getSSOPublicService(ServletConfig servlet) {
        String publicSsoUrl = getConfig(servlet, SSOConstants.ClientConfig.PUBLIC_SSO_SERVER);
        if (StringSelfUtil.isNotBlank(publicSsoUrl)) {
            return SsoUrlUtil.getRootDomain(publicSsoUrl);
        }
        return SsoUrlUtil.getRootDomain(getConfig(servlet.getServletContext(), SSOConstants.ClientConfig.PUBLIC_SSO_SERVER));
    }

    public static String getSSOPublicService(FilterConfig filterConfig) {
        String publicSsoUrl = getConfig(filterConfig, SSOConstants.ClientConfig.PUBLIC_SSO_SERVER);
        if (StringSelfUtil.isNotBlank(publicSsoUrl)) {
            return SsoUrlUtil.getRootDomain(publicSsoUrl);
        }
        return SsoUrlUtil.getRootDomain(getConfig(filterConfig.getServletContext(), SSOConstants.ClientConfig.PUBLIC_SSO_SERVER));
    }


    public static String getConfig(ServletContext servletContext, String key) {
        return StringSelfUtil.trim(servletContext.getInitParameter(key));
    }

    public static String getConfig(FilterConfig filterConfig, String key) {
        return StringSelfUtil.trim(filterConfig.getInitParameter(key));
    }

    public static String getConfig(ServletConfig servlet, String key) {
        return StringSelfUtil.trim(servlet.getInitParameter(key));
    }

    public static Set<String> getSets(FilterConfig filterConfig, String key) {
        return StringSelfUtil.split(filterConfig.getInitParameter(key), StringSelfUtil.SPLIT_COMMA);
    }

    public static Set<String> getSets(ServletConfig servlet, String key) {
        return StringSelfUtil.split(servlet.getInitParameter(key), StringSelfUtil.SPLIT_COMMA);
    }

    public static Boolean getBoolean(ServletConfig servlet, String key) {
        String property = servlet.getInitParameter(key);
        if (StringSelfUtil.equalsIgnoreTrimCase("true", property)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    public static Boolean getBoolean(FilterConfig filterConfig, String key) {
        String property = filterConfig.getInitParameter(key);
        if (StringSelfUtil.equalsIgnoreTrimCase("true", property)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
